define([
    'dojo/dom',
    'dojo/when',
    'dijit/registry',
    'dojo/window',
    'dojo/parser',
    'cbtree/model/TreeStoreModel',
    'cbtree/store/Hierarchy',
    'dijit/_editor/plugins/FontChoice',
    //
    'dijit/_editor/plugins/ViewSource',
    'dojox/editor/plugins/PrettyPrint',
    'dijit/_editor/plugins/LinkDialog',
    'dijit/_editor/plugins/TextColor',
    'dojox/editor/plugins/FindReplace',
    'dojox/editor/plugins/PasteFromWord',
    'dojox/editor/plugins/Preview',
    //
    'xstyle/css!dijit/themes/claro/claro.css',
    'xstyle/css!dojox/form/resources/FileInput.css',
    'xstyle/css!dojox/layout/resources/ExpandoPane.css',
    'xstyle/css!cbtree/themes/claro/claro.css',
    'xstyle/css!dojox/editor/plugins/resources/css/FindReplace.css',
    'xstyle/css!dojox/editor/plugins/resources/css/PasteFromWord.css',
    'xstyle/css!dojox/editor/plugins/resources/css/Preview.css'
], function (dom,
             when,
             registry,
             dojoWindow,
             parser,
             TreeStoreModel,
             Hierarchy,
             FontChoice) {
    var EDITOR_BODY_ID = 'dijitEditorBody';
    var DOC_TITLE_BOX_ID = 'docTitle';
    var treeRoot = {id: 1};
    var initialized = false;
    var editor = window.editor = null;
    var treeStore = new Hierarchy({data: [treeRoot]});
    var anchorStack = null;

    FontChoice._FormatBlockDropDown.extend({
        values: ["noFormat", "p", "h1", "h2", "h3", "h4", "h5", "h6"]
    });

    function setTreeData(data) {
        treeStore.close(true);
        return treeStore.load({data: data});
    }

    /**
     *
     * @param node must be an element node
     */
    function dealNode(node) {
        if (node.nodeType == Node.ELEMENT_NODE) {
            var tagName = node.tagName.toUpperCase();
            switch (tagName) {
                case 'H1':
                case 'H2':
                case 'H3':
                case 'H4':
                case 'H5':
                case 'H6':
                    //navigator
                    var anchorLabel = (node.textContent || node.innerText || '').trim(); //IE or other browser
                    var anchor = {
                        name: anchorLabel,
                        tagName: tagName,
                        id: treeStore._data.length + 1,
                        node: node
                    };
                    while (tagName <= anchorStack[anchorStack.length - 1].tagName) {
                        anchorStack.pop();
                    }
                    anchor.parent = anchorStack[anchorStack.length - 1].id;
                    anchorStack.push(anchor);
                    treeStore.put(anchor);
                    break;
                default: //ignore other elements, such as img
                    break;
            }
            var children = node.childNodes;
            if (children) {
                for (var i = 0; i < children.length; i++) {
                    dealNode(children);
                }
            }
        }
    }

    function beforeParse() {
        window.navigatorModel = new TreeStoreModel({
            store: treeStore,
            query: {id: treeRoot.id}
        });

        window.loadDoc = function () {
            if (initialized) {
                var file = registry.byId('fileInput').fileInput.files[0];
                if (!file) {
                    alert('未选择任何文件!');
                } else if (typeof FileReader == 'undefined') {
                    alert('当前浏览器不支持文件读取接口FileReader，请更换符合html5标准的浏览器!');
                } else {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var content = e.target.result;
                        editor.set('value', content);
                        generateNav();
                    };
                    var encoding = dom.byId('encodingSelect').value;
                    reader.readAsText(file, encoding);
                }
            }
        };

        window.generateNav = function () {
            if (initialized) {
                //reset navigator
                anchorStack = [treeRoot];
                setTreeData([treeRoot]);
                //read data
                var htmlRoot;
                var doc = editor.document;
                htmlRoot = doc.getElementById(EDITOR_BODY_ID);
                //doc title
                if (doc.title)
                    registry.byId(DOC_TITLE_BOX_ID).set('value', doc.title);
                //doc content
                var children = htmlRoot.childNodes;
                for (var i = 0; i < children.length; i++) {
                    dealNode(children[i]);
                }
                setTreeData(treeStore._data);
                //registry.byId(EDITOR_ID).set('value', htmlRoot.innerHTML);
            }
        };

        window.navigatorClick = function (item, nodeWidget) {
            if (item.node) {
                dojoWindow.scrollIntoView(item.node);
            }
        };

        window.saveTitleToEditor = function () {
            if (initialized) {
                setTimeout(function () {
                    var newTitle = registry.byId(DOC_TITLE_BOX_ID).get('value');
                    editor.document.title = newTitle;
                }, 0);
            }
        };

        window.saveDoc = function () {
            if (initialized) {
                dom.byId('content').value = editor.get('value');
            }
        };

        window.openWindowWithName = function (windowName) {
            window.open('about:blank', windowName);
        }
    }

    return function () {
        when(beforeParse())
            .then(function () {
                return parser.parse();
            })
            .then(function () {
                editor = registry.byId('editor');
                registry.byId('mainBorderLayout').resize();
                initialized = true;
            });
    };
});
